package com.bj58.wuxian.lucene.pinyin;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.junit.Before;
import org.junit.Test;

import com.bj58.wuxian.lucene.utils.LuceneUtil;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class MyTest {
	
	private Analyzer analyzer;
	private Directory directory;
	
	@Before
	public void init() throws IOException {
		analyzer = new StandardAnalyzer();

		// 在内存中 创建索引
		// directory = new RAMDirectory();
		// 在磁盘中创建索引
		directory = LuceneUtil.getDirectory("D:\\index");
	}
	
	@Test
	public void testSearchByPinyin() throws ParseException, IOException, BadHanyuPinyinOutputFormatCombination{

			DirectoryReader ireader = DirectoryReader.open(directory);
			IndexSearcher isearcher = new IndexSearcher(ireader);

			QueryParser parser = new QueryParser("title", analyzer);
			Query query = parser.parse("三国演义");
			
			String pinyin=Pinyin4jUtil.hanziToPinyin("三国演义");
			Query pinyinQuery = parser.parse(pinyin);
			BooleanClause booleanClause1=new BooleanClause(pinyinQuery, Occur.SHOULD);
			BooleanClause booleanClause2=new BooleanClause(query, Occur.SHOULD);
			BooleanQuery booleanQuery =new BooleanQuery.Builder()
					.add(booleanClause1)
					.add(booleanClause2).build();
			
			ScoreDoc[] hits = isearcher.search(booleanQuery, 10).scoreDocs;

			for (int i = 0; i < hits.length; i++) {
				Document hitDoc = isearcher.doc(hits[i].doc);
				System.out.println("id： " + hitDoc.get("id") + "  title:" + hitDoc.get("title") + "   author:"
						+ hitDoc.get("author")+ "   price:" + hitDoc.get("price") + "   desc:" + hitDoc.get("desc")+"  得分:"+hits[i].score);
			}
			ireader.close();
			directory.close();
	}

}
